package com.taimi.newdemo.service;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.UUID;

import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class OpenvpnService {

    private static final String OPENVPN_SUFFIX = ".ovpn";

    public String generateOpenvpnClient(String clientName) throws IOException, InterruptedException {
        Runtime runtime = Runtime.getRuntime();
        if (!StringUtils.hasText(clientName)) {
            clientName = UUID.randomUUID().toString();
        }
        String[] cmdArray = { "sh", "add-new-user.sh", "1", clientName };
        Path path = Paths.get(System.getProperty("user.dir"));
        Process process = runtime.exec(cmdArray, null, path.toFile());

        // 等待命令执行结束
        process.waitFor();
        return path.resolve(getFileName(clientName)).toString();
    }

    private String getFileName(String clientName) {
        return clientName.concat(OPENVPN_SUFFIX);
    }

    public ResponseEntity<FileSystemResource> export(File file) {
        if (file == null) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment; filename=" + file.getName());
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Last-Modified", LocalDateTime.now().toString());
        headers.add("ETag", String.valueOf(System.currentTimeMillis()));
        headers.add("filename", file.getName());
        return ResponseEntity.ok().headers(headers).contentLength(file.length())
                .contentType(MediaType.APPLICATION_OCTET_STREAM).body(new FileSystemResource(file));
    }

}
